from appserver import db_store
import traceback

# from models.entity.button import Button


class ProjectItemWithSensor(db_store.Model):
	__tablename__="projectitem_with_sensors"
	__bind_key__="main"

	# id=db_store.Column(db_store.Integer,primary_key=True)
	project_item_id=db_store.Column(db_store.Integer,db_store.ForeignKey("project_items.id"),nullable=False,primary_key=True)
	sensor_id=db_store.Column(db_store.Integer,db_store.ForeignKey("sensors.id"),nullable=False,primary_key=True)

	def __repr__(self):
		return "<ProjectWithSensor %d+%d>" %(self.project_id,self.sensor_id)

	def save(self):
		if self.project_item_id is None:
			print("ProjectWithSensor save error: project_item_id cannot be empty")
			return -1
		if self.sensor_id is None:
			print("ProjectWithSensor save error: sensor_id cannot be empty")
			return -2
		try:
			db_store.session.add(self)
			db_store.session.commit()
			return 0
		except:
			print("table projects_with_sensors write error:\n--------------------\n%s\n----------------------" %(traceback.format_exc()))
			db_store.session.rollback()
			return -3

	def delete(self):
		# id=self.id
		try:
			db_store.session.delete(self)
			db_store.session.commit()
			return 0
		except:
			print("ProjectWithSensor(id=%d) delete  error:\n-------------------\n%s\n----------------------" (id,traceback.format_exc()))
			db_store.session.rollback()
			return -1

	@staticmethod
	def add_sensors_to_project_item(project_item_id, sensor_ids):
		# 向指定用户添加一组按钮
		# 用法:
		#       role_id 角色id
		#       modules 模型id的列表
		for item in sensor_ids:
			sensor_connector = ProjectItemWithSensor()
			sensor_connector.project_item_id = project_item_id
			sensor_connector.sensor_id = item
			if sensor_connector.save() != 0:
				return -1
		return 0